package com.gzhryc.shared_device.pcl.core.decoders;

import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.secruity.EncryptTools;
import com.gzhryc.shared_device.pcl.core.PwdDecodeFactory;
import com.gzhryc.shared_device.pcl.core.PwdResult;

public class GZXJ510Decoder implements PwdDecodeFactory.Decoder {

	final static Logger log = Logger.getLogger(GZXJ510Decoder.class);

	/** 骁匠5键密码 */
	public static final String KEY_DECODE_TYPE = "GZXJ_PCL05";

	/**
	 * @param deviceSn   设备序列号
	 * @param key        密钥
	 * @param indexStr   密码序号
	 * @param setMealNum 套餐序号
	 */
	public PwdResult getPwd(String deviceSn, String key, String indexStr, Integer setMealNum, Object extendData) {
		PwdResult result = new PwdResult();
		try {
			Integer index = Integer.valueOf(indexStr);
			if (index > 20 || index <= 0) {
				index = 1; // 重置密码
			}
			String pwdIndex = String.format("%02d", index);
			String md5 = key + deviceSn + pwdIndex;
			md5 = EncryptTools.md5(md5);
			String temp1 = md5.substring(md5.length() - 3);
			Integer val1 = Integer.valueOf(temp1, 16);
			int pwd1 = ((val1 >> 9) & 0x7) % 5 + 1;
			int pwd2 = ((val1 >> 6) & 0x7) % 5 + 1;
			int pwd3 = ((val1 >> 3) & 0x7) % 5 + 1;
			int pwd4 = (val1 & 0x7) % 5 + 1;
			String pwd = "" + pwd1 + pwd2 + pwd3 + pwd4;
			// 遇到这几个密码重新累计
			if (pwd.equals("1111") || pwd.equals("2222") || pwd.equals("3333") || pwd.equals("4444") || pwd.equals("5555")) {
				index = index + 1;
				return getPwd(deviceSn, key, index.toString(), setMealNum,extendData);
			}

			result.setSuccess(true);
			result.setCurrentIndex(index);
			index = index + 1;
			if (index > 20) {
				index = 1; // 重置密码
			}
			pwd = setMealNum + pwd;
			result.setPwd(pwd);
			result.setIndex(index.toString());// 下一组密码序号
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}

	@Override
	public String getKey() {
		return KEY_DECODE_TYPE;
	}
}
